#!/usr/bin/env python

# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Street Identity Console Model."""

from google.appengine.ext import db

__author__ = 'Maciej Machulak'
__maintainer__ = 'Maciej Machulak'
__email__ = 'mmachulak@google.com'

__copyright__ = 'Copyright 2012, Google Inc.'
__license__ = 'Apache License 2.0'
__version__ = '0.3'
__status__ = 'Prototype'


class User(db.Model):
  """Local user at Street Identity console."""

  user_id = db.StringProperty(required=True)
  email = db.StringProperty()
  display_name = db.StringProperty()
  refresh_token = db.StringProperty()

  def delete(self):
    """Remove all attribute providers registered for this user."""

    for single_ap in self.ap_list:
      single_ap.delete()
    db.delete(self)


class Session(db.Model):
  """Login session of the user."""
  # TODO(mmachulak) - use gaesessions

  id = db.StringProperty(required=True)
  user = db.ReferenceProperty(User)
  access_token = db.StringProperty()
  credentials = db.BlobProperty()


class Application(db.Model):
  """Attribute Provider or Relying Party."""

  client_id = db.StringProperty(required=True)
  name = db.StringProperty(default='Unknown Application')
  url = db.StringProperty()
  icon_url = db.StringProperty()

  def delete(self):
    """Delete relationships with the user."""

    for single_ap in self.ap_list:
      single_ap.delete()
    db.delete(self)


class AttributeProvider(db.Model):
  """Attribute Provider registered for the user."""

  application = db.ReferenceProperty(Application, required=True)
  user = db.ReferenceProperty(User, collection_name='ap_list',
                              required=True)
  scopes = db.StringListProperty(required=True)

  def delete(self):
    """Delete all authorizations for this attribute."""

    for authorization in self.authorization_list:
      authorization.delete()
    db.delete(self)


class Authorization(db.Model):
  """Authorization issued by IDP to access AP for specific user."""

  application = db.ReferenceProperty(Application, required=True)
  attribute_provider = db.ReferenceProperty(AttributeProvider,
                                   collection_name='authorization_list',
                                   required=True)
  iat = db.IntegerProperty(required=True)
  exp = db.IntegerProperty(required=True)
  scopes = db.StringListProperty(required=True)
  token_hash = db.StringProperty()
